package com.hgvip.autoCommit;

import com.hgvip.common.KafkaParams;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * Created by arnold.zhu on 2017/8/3.
 */
public class Consumer {

    private static Logger logger = LoggerFactory.getLogger(Consumer.class);

    public static void main(String[] args) throws InterruptedException {
        Properties props = new Properties();
        props.put("bootstrap.servers", KafkaParams.BOOTSTRAP_SERVERS);
        props.put("group.id", KafkaParams.GROUP_ID);
        // 设置enable.auto.commit,偏移量由auto.commit.interval.ms控制自动提交的频率。
        props.put("enable.auto.commit", KafkaParams.ENABLE_AUTO_COMMIT);
        props.put("auto.commit.interval.ms", KafkaParams.AUTO_COMMIT_INTERVAL_MS);
        props.put("key.deserializer", KafkaParams.KEY_DESERIALIZER);
        props.put("value.deserializer", KafkaParams.VALUE_DESERIALIZER);
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        // 订阅my-topic22
        // kafka将已订阅topic的消息发送到每个消费者组中。并通过平衡分区在消费者分组中所有成员之间来达到平均。
        consumer.subscribe(Collections.singletonList("my-topic22"));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                logger.info("offset = " + record.offset() + ", key = " + record.key() + ", value = " + record.value());
            }
        }
    }

}
